/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tubes1sister.peerConnection.message;

/**
 *
 * @author Muhammad Anis
 */
//message handshake yang pertama kali dikirimkan, intinya adalah mengirimkan kepada
//client lain apakah dia memiliki pieces yang diinginkan oleh client lain
public class Handshake {

    public int pstrlen = 19;
    public String pstr = "BitTorrentProtocol";
    public byte[] reserved = new byte[8];
    public String filename;
    public int pieceIndex;

    //konstruktor
    public Handshake(String filename,int pieceIndex) {
        this.filename = filename;
        this.pieceIndex = pieceIndex;
    }

    //generate message
    public String generateMessage() {
        String ret = "";
        ret += Integer.toString(pstrlen);
        ret += pstr;
        ret += new String(reserved);
        ret += "@";
        ret += filename;
        ret +="!";
        ret +=Integer.toString(this.pieceIndex);
        return ret;
    }

    //fungsi untuk mendapatkan filename dari sebuah handshake message
    public static String parseHandshakeMessage(String handshakemessage) {
        int index = handshakemessage.indexOf("@");
        int lastIndex = handshakemessage.indexOf("!");
        if (index != -1) {
            return handshakemessage.substring(index + 1,lastIndex);
        } else {
            return null;
        }
    }

    public static int getPieceIndex(String handshake){
        int index = handshake.indexOf("!");
        if (index != -1) {
            return Integer.parseInt(handshake.substring(index + 1));
        } else {
            return -999;
        }
    }
}
